from .utils import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import *
from rest_framework.parsers import MultiPartParser, JSONParser
from rest_framework.permissions import IsAuthenticated
from .serializers import *
from rest_framework import viewsets
from rest_framework.decorators import action
import logging
from django.http import HttpResponse
from django.conf import settings
from .base import BaseOrderViewSet
from .shipping import *
from utils.pagination import MyPageNumberPagination
from rest_framework.generics import GenericAPIView
from rest_framework import serializers
from django.db import models
from django.db.models import Q, Sum, Count
from django.utils import timezone
from datetime import datetime, timedelta
import os
import zipfile
import tempfile


logger = logging.getLogger(__name__)


# 本地订单视图集
class LocalOrderViewSet(BaseOrderViewSet):
    queryset = LocalOrder.objects.all()
    serializer_class = LocalOrderSerializer
    search_field = 'fs_no'  # 用于搜索的字段

    # 从Excel文件导入本地订单   
    @action(methods=['POST'], detail=False, url_path='import')
    def import_orders(self, request, *args, **kwargs):
        try:
            if 'file' not in request.FILES:
                return Response({'code': 400,'message': '请上传.xls文件'}, status=status.HTTP_400_BAD_REQUEST)   
            serializer = self.get_serializer()
            result = serializer.process_excel_import(request.FILES['file'], request.user)            
            return Response({'code': 200,'message': '导入完成','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'导入失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 批量删除本地订单
    @action(methods=['POST'], detail=False, url_path='batch_delete')
    def batch_delete(self, request, *args, **kwargs):
        try:
            fs_no_list = request.data.get('fs_no', [])
            serializer = self.get_serializer()
            result = serializer.process_batch_delete(fs_no_list)
            return Response({'code': 200,'message': '批量删除成功','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'批量删除失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 导出本地订单
    @action(methods=['POST'], detail=False, url_path='export')
    def export(self, request, *args, **kwargs):
        try:
            ids = request.data.get('ids', [])
            local_orders = LocalOrder.objects.filter(id__in=ids)
            return export_orders_to_excel(local_orders, '本地订单')
        except Exception as e:
            return Response({'code': 500,'message': f'导出失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 批量更新创建日期
    @action(methods=['POST'], detail=False, url_path='batch_update_date')
    def batch_update_date(self, request, *args, **kwargs):
        try:
            fs_no_list = request.data.get('fs_no', [])
            create_time = request.data.get('create_time', '')
            serializer = self.get_serializer()
            result = serializer.process_batch_update_date(fs_no_list, create_time)
            return Response({'code': 200,'message': '批量更新日期成功','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'批量更新日期失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
          

# 邮政编码搜索视图
class PostalCodeSearchView(APIView):
    permission_classes = [IsAuthenticated]
    
    def post(self, request):
        try:
            # 获取请求数据
            postal_code_list = request.data
            if not isinstance(postal_code_list, list):
                return Response({'code': 400, 'message': '无邮编'}, status=status.HTTP_400_BAD_REQUEST)

            # 分离fs_no和cw_no的数据
            fs_no_list = []
            cw_no_list = []
            
            for item in postal_code_list:
                if 'fs_no' in item and item['fs_no']:
                    fs_no_list.append(item)
                elif 'cw_no' in item and item['cw_no']:
                    cw_no_list.append(item)
            
            # 分别处理两种类型的订单
            local_results, local_errors = batch_search_postal_codes(fs_no_list, LocalOrder) if fs_no_list else ([], [])
            transfer_results, transfer_errors = batch_search_postal_codes(cw_no_list, TransferOrder) if cw_no_list else ([], [])
            
            # 合并结果
            all_results = local_results + transfer_results
            all_errors = local_errors + transfer_errors
            
            return Response({
                'code': 200,
                'message': '处理完成',
                'data': {
                    'success_count': len(all_results),
                    'error_count': len(all_errors),
                    'results': all_results,
                    'errors': all_errors
                }
            })
            
        except Exception as e:
            return Response({'code': 500, 'message': f'处理失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 运费计算视图
class ShippingMethodView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取请求中的FS编号列表和CW编号列表
        fs_no_list = request.data.get('fs_no', [])
        cw_no_list = request.data.get('cw_no', [])
        
        # 如果没有提供FS编号列表和CW编号列表，则返回错误信息
        if not fs_no_list and not cw_no_list:
            return Response({'code': 400, 'message': '请提供FS编号列表或CW编号列表'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            results = []
            errors = []
            
            # 处理本地订单
            if fs_no_list:
                local_results, local_errors = calculate_shipping_fee(fs_no_list, LocalOrder)
                results.extend(local_results)
                errors.extend(local_errors)
            
            # 处理转运订单
            if cw_no_list:
                transfer_results, transfer_errors = calculate_shipping_fee(cw_no_list, TransferOrder)
                results.extend(transfer_results)
                errors.extend(transfer_errors)

            # 返回处理结果
            return Response({
                'code': 200,
                'message': '处理完成',
                'data': {
                    'success_count': len(results),
                    'error_count': len(errors),
                    'results': results,
                    'errors': errors
                }
            })
            
        except Exception as e:
            # 如果发生异常，则返回错误信息
            return Response({
                'code': 500,
                'message': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 转运订单视图集
class TransferOrderViewSet(BaseOrderViewSet):
    queryset = TransferOrder.objects.all()
    serializer_class = TransferOrderSerializer
    search_field = 'cw_no'  # 用于搜索的字段

    @action(methods=['POST'], detail=False, url_path='import')
    def import_orders(self, request):
        """
        从Excel文件导入转运订单
        """
        try:
            if 'file' not in request.FILES:
                return Response({'code': 400,'message': '请上传文件'}, status=status.HTTP_400_BAD_REQUEST)
            serializer = self.get_serializer()
            result = serializer.process_excel_import(request.FILES['file'], request.user)
            return Response({'code': 200,'message': '导入完成','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'导入失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['POST'], detail=False, url_path='generate-pdf')
    def generate_pdf(self, request, *args, **kwargs):
        try:
            orders_data = request.data.get('orders', [])
            carrier = request.data.get('carrier', '')
            
            # 生成PDF
            pdf_content = generate_transfer_receipt_pdf(orders_data, carrier, request.user.username)
            
            # 保存PDF到后台
            saved_file_path = self._save_pdf_to_backend(pdf_content, request.user.username, carrier)
            
            # 创建响应
            response = HttpResponse(pdf_content, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="transfer_orders.pdf"'
            response['Access-Control-Expose-Headers'] = 'Content-Disposition'
            response['Content-Length'] = len(pdf_content)
            
            # 在响应头中添加保存的文件路径信息
            response['X-Saved-File-Path'] = saved_file_path
            
            return response   
        except Exception as e:
            return Response({'code': 500,'message': f'生成PDF失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def _save_pdf_to_backend(self, pdf_content, username, carrier):
        """保存PDF到后台"""
        # 创建保存目录：media/pdf/日期/日期_用户名_承运商.pdf
        today = datetime.now().strftime('%Y-%m-%d')
        save_dir = os.path.join(settings.MEDIA_ROOT, 'pdf', today)
        
        # 确保目录存在
        os.makedirs(save_dir, exist_ok=True)
        
        # 生成文件名：日期_用户名_承运商.pdf
        filename = f"{today}_{username}_{carrier}.pdf"
        file_path = os.path.join(save_dir, filename)
        
        # 保存文件
        with open(file_path, 'wb') as f:
            f.write(pdf_content)
        
        # 返回相对路径
        relative_path = os.path.join('pdf', today, filename)
        return relative_path

    @action(methods=['POST'], detail=False, url_path='save-pdf')
    def save_pdf(self, request, *args, **kwargs):
        """保存PDF到后台的独立API"""
        try:
            orders_data = request.data.get('orders', [])
            carrier = request.data.get('carrier', '')
            
            # 生成PDF
            pdf_content = generate_transfer_receipt_pdf(orders_data, carrier, request.user.username)
            
            # 保存PDF到后台
            saved_file_path = self._save_pdf_to_backend(pdf_content, request.user.username, carrier)
            
            return Response({
                'code': 200,
                'message': 'PDF保存成功',
                'data': {
                    'file_path': saved_file_path,
                    'file_url': f"{settings.MEDIA_URL}{saved_file_path}"
                }
            })
        except Exception as e:
            return Response({'code': 500,'message': f'保存PDF失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['GET'], detail=False, url_path='saved-pdfs')
    def get_saved_pdfs(self, request, *args, **kwargs):
        """获取保存的PDF列表"""
        try:
            
            # 获取查询参数
            start_date_str = request.query_params.get('start_date')
            end_date_str = request.query_params.get('end_date')
            days = int(request.query_params.get('days', 7))  # 默认获取最近7天
            
            # 计算日期范围
            if start_date_str and end_date_str:
                # 使用指定的日期范围
                start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
                end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
            else:
                # 使用天数计算日期范围
                end_date = datetime.now()
                start_date = end_date - timedelta(days=days)
            
            pdf_files = []
            base_dir = os.path.join(settings.MEDIA_ROOT, 'pdf')
            
            # 遍历日期目录
            current_date = start_date
            while current_date <= end_date:
                date_str = current_date.strftime('%Y-%m-%d')
                date_dir = os.path.join(base_dir, date_str)
                
                if os.path.exists(date_dir):
                    for filename in os.listdir(date_dir):
                        if filename.endswith('.pdf'):
                            file_path = os.path.join(date_dir, filename)
                            file_stat = os.stat(file_path)
                            
                            # 解析文件名获取信息
                            name_parts = filename.replace('.pdf', '').split('_')
                            if len(name_parts) >= 3:
                                file_date, username, carrier = name_parts[0], name_parts[1], '_'.join(name_parts[2:])
                                
                                pdf_files.append({
                                    'filename': filename,
                                    'file_path': os.path.join('pdf', date_str, filename),
                                    'file_url': f"{settings.MEDIA_URL}pdf/{date_str}/{filename}",
                                    'date': file_date,
                                    'username': username,
                                    'carrier': carrier,
                                    'size': file_stat.st_size,
                                    'created_time': datetime.fromtimestamp(file_stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
                                })
                
                current_date += timedelta(days=1)
            
            # 按创建时间倒序排列
            pdf_files.sort(key=lambda x: x['created_time'], reverse=True)
            
            return Response({
                'code': 200,
                'message': '获取PDF列表成功',
                'data': pdf_files
            })
        except Exception as e:
            return Response({'code': 500,'message': f'获取PDF列表失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['DELETE'], detail=False, url_path='delete-pdf')
    def delete_pdf(self, request, *args, **kwargs):
        """删除单个PDF文件"""
        try:
            file_path = request.data.get('file_path')
            if not file_path:
                return Response({'code': 400,'message': '文件路径不能为空'}, status=status.HTTP_400_BAD_REQUEST)
            
            # 构建完整的文件路径
            full_path = os.path.join(settings.MEDIA_ROOT, file_path)
            
            # 检查文件是否存在
            if not os.path.exists(full_path):
                return Response({'code': 404,'message': '文件不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            # 删除文件
            os.remove(full_path)
            
            return Response({
                'code': 200,
                'message': '文件删除成功'
            })
        except Exception as e:
            return Response({'code': 500,'message': f'删除文件失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['POST'], detail=False, url_path='batch-delete-pdfs')
    def batch_delete_pdfs(self, request, *args, **kwargs):
        """批量删除PDF文件"""
        try:
            
            file_paths = request.data.get('file_paths', [])
            if not file_paths:
                return Response({'code': 400,'message': '文件路径列表不能为空'}, status=status.HTTP_400_BAD_REQUEST)
            
            deleted_files = []
            failed_files = []
            
            for file_path in file_paths:
                try:
                    # 构建完整的文件路径
                    full_path = os.path.join(settings.MEDIA_ROOT, file_path)
                    
                    # 检查文件是否存在
                    if os.path.exists(full_path):
                        os.remove(full_path)
                        deleted_files.append(file_path)
                    else:
                        failed_files.append({'file': file_path, 'reason': '文件不存在'})
                except Exception as e:
                    failed_files.append({'file': file_path, 'reason': str(e)})
            
            return Response({
                'code': 200,
                'message': f'批量删除完成，成功删除 {len(deleted_files)} 个文件',
                'data': {
                    'deleted_files': deleted_files,
                    'failed_files': failed_files
                }
            })
        except Exception as e:
            return Response({'code': 500,'message': f'批量删除失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['POST'], detail=False, url_path='batch-download-pdfs')
    def batch_download_pdfs(self, request, *args, **kwargs):
        """批量下载PDF文件（打包成ZIP）"""
        try:
            
            file_paths = request.data.get('file_paths', [])
            if not file_paths:
                return Response({'code': 400,'message': '文件路径列表不能为空'}, status=status.HTTP_400_BAD_REQUEST)
            
            # 创建临时ZIP文件
            temp_zip = tempfile.NamedTemporaryFile(delete=False, suffix='.zip')
            
            with zipfile.ZipFile(temp_zip.name, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for file_path in file_paths:
                    full_path = os.path.join(settings.MEDIA_ROOT, file_path)
                    if os.path.exists(full_path):
                        # 获取文件名（不包含路径）
                        filename = os.path.basename(file_path)
                        zipf.write(full_path, filename)
            
            # 读取ZIP文件内容
            with open(temp_zip.name, 'rb') as f:
                zip_content = f.read()
            
            # 删除临时文件
            os.unlink(temp_zip.name)
            
            # 创建响应
            response = HttpResponse(zip_content, content_type='application/zip')
            response['Content-Disposition'] = 'attachment; filename="pdf_files.zip"'
            response['Access-Control-Expose-Headers'] = 'Content-Disposition'
            
            return response
        except Exception as e:
            return Response({'code': 500,'message': f'批量下载失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['POST'], detail=False, url_path='batch_delete')
    def batch_delete(self, request, *args, **kwargs):
        try:
            cw_no_list = request.data.get('cw_no', [])
            serializer = self.get_serializer()
            result = serializer.process_batch_delete(cw_no_list)
            return Response({'code': 200,'message': '批量删除成功','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'批量删除失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['POST'], detail=False, url_path='export')
    def export(self, request, *args, **kwargs):
        try:
            ids = request.data.get('ids', [])
            transfer_orders = TransferOrder.objects.filter(id__in=ids)
            return export_orders_to_excel(transfer_orders, '转运订单')
        except Exception as e:
            return Response({'code': 500,'message': f'导出失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 批量更新创建日期
    @action(methods=['POST'], detail=False, url_path='batch_update_date')
    def batch_update_date(self, request, *args, **kwargs):
        try:
            cw_no_list = request.data.get('cw_no', [])
            create_time = request.data.get('create_time', '')
            serializer = self.get_serializer()
            result = serializer.process_batch_update_date(cw_no_list, create_time)
            return Response({'code': 200,'message': '批量更新日期成功','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'批量更新日期失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 退换货单视图集
class AfterSaleOrderViewSet(BaseOrderViewSet):
    queryset = AfterSaleOrder.objects.all()
    serializer_class = AfterSaleOrderSerializer
    search_field = 'cs_no'  # 用于搜索的字段

    @action(methods=['POST'], detail=False, url_path='import')
    def import_orders(self, request, *args, **kwargs):
        """
        从Excel文件导入售后订单
        """
        try:
            if 'file' not in request.FILES:
                return Response({'code': 400,'message': '请上传文件'}, status=status.HTTP_400_BAD_REQUEST)
            serializer = self.get_serializer()
            result = serializer.process_excel_import(request.FILES['file'], request.user)
            return Response({'code': 200,'message': '导入成功','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'导入失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 调仓单视图集
class RelocationOrderViewSet(BaseOrderViewSet):
    queryset = RelocationOrder.objects.all()
    serializer_class = RelocationOrderSerializer


# 跨仓单视图集
class CrossOrderViewSet(BaseOrderViewSet):
    queryset = CrossOrder.objects.all()
    serializer_class = CrossOrderSerializer


# 回国单视图集
class ReturnOrderViewSet(BaseOrderViewSet):
    queryset = ReturnOrder.objects.all()
    serializer_class = ReturnOrderSerializer


# 库存收获单视图集
class InventoryReceiveOrderViewSet(BaseOrderViewSet):
    queryset = InventoryReceiveOrder.objects.all()
    serializer_class = InventoryReceiveOrderSerializer
        

# 维修单视图集
class RepairOrderViewSet(BaseOrderViewSet): 
    queryset = RepairOrder.objects.all()
    serializer_class = RepairOrderSerializer


# 报表视图集
class ReportViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]
    parser_classes = (MultiPartParser, JSONParser)
    
    def get_serializer_class(self):
        if self.action == 'unprocessed_orders':
            return UnprocessedOrderSerializer
        return ReportSerializer

    def list(self, request):
        try:
            start_date = request.query_params.get('start_date')
            end_date = request.query_params.get('end_date')
            serializer = ReportSerializer()
            result = serializer.get_report_data(start_date, end_date)
            return Response({'code': 200,'message': '报表生成成功','data': result})
        except Exception as e:
            return Response({'code': 500,'message': f'获取报表数据失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['GET', 'POST'], detail=False, url_path='unprocessed-orders')
    def unprocessed_orders(self, request):
        try:
            serializer = UnprocessedOrderSerializer()
            
            if request.method == 'POST':
                result = serializer.save_unprocessed_orders_data(request.data, request.user)
                return Response({'code': 200,'message': '未处理订单统计数据保存成功','data': result})
            else:
                start_date = request.query_params.get('start_date')
                end_date = request.query_params.get('end_date')
                result = serializer.get_unprocessed_orders_data(start_date, end_date)
                return Response({'code': 200,'message': '获取成功','data': result})
        except ValueError as e:
            return Response({'code': 400,'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500,'message': f'操作失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['GET'], detail=False, url_path='daily')
    def get_daily_report(self, request):
        try:
            start_date = request.query_params.get('start_date')
            end_date = request.query_params.get('end_date')
            serializer = ReportSerializer()
            result = serializer.get_daily_report(start_date, end_date)
            return Response({'code': 200,'message': '获取日报表成功','data': result})
        except Exception as e:
            return Response({'code': 500,'message': f'获取日报表失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['GET'], detail=False, url_path='export/excel')
    def export_excel(self, request):
        try:
            start_date = request.query_params.get('start_date')
            end_date = request.query_params.get('end_date')
            serializer = ReportSerializer()
            return serializer.export_excel_report(start_date, end_date)
        except Exception as e:
            return Response({'code': 500,'message': f'导出失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# 备注视图
class RemarkView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    pagination_class = MyPageNumberPagination
    
    def get(self, request):
        # 获取本地订单数据（过滤有备注的）
        local_orders_queryset = LocalOrder.objects.select_related('created_by')\
            .filter(remark__isnull=False)\
            .exclude(remark='')\
            .order_by('-create_time')
        
        # 对本地订单进行分页
        local_page = self.paginate_queryset(local_orders_queryset)
        
        local_order_remark_list = []
        if local_page is not None:
            for local_order in local_page:
                local_order_remark_list.append({'remark': local_order.remark,'fs_no': local_order.fs_no,'create_time': local_order.create_time.strftime('%Y-%m-%d'),'create_user': local_order.created_by.username if local_order.created_by else '','remark_status': local_order.remark_status,'shipping_method': local_order.shipping_method})

        # 获取转运订单数据（过滤有备注的）
        transfer_orders_queryset = TransferOrder.objects.select_related('created_by')\
            .filter(remark__isnull=False)\
            .exclude(remark='')\
            .order_by('-create_time')
        
        # 对转运订单进行分页
        transfer_page = self.paginate_queryset(transfer_orders_queryset)
        
        transfer_order_remark_list = []
        if transfer_page is not None:
            for transfer_order in transfer_page:
                transfer_order_remark_list.append({'remark': transfer_order.remark,'cw_no': transfer_order.cw_no,'create_time': transfer_order.create_time.strftime('%Y-%m-%d'),'create_user': transfer_order.created_by.username if transfer_order.created_by else '','remark_status': transfer_order.remark_status,'shipping_method': transfer_order.shipping_method})

        # 返回分页响应
        return self.get_paginated_response({'local_order_remark_list': local_order_remark_list,'transfer_order_remark_list': transfer_order_remark_list})


# 运费配置视图集
class FeeViewSet(viewsets.GenericViewSet):
    permission_classes = []
    pagination_class = MyPageNumberPagination

    def list(self, request):
        try:
            carrier = request.query_params.get('carrier', '').strip()
            volume = request.query_params.get('volume', '').strip()
            region = request.query_params.get('region', '').strip()
            is_active = request.query_params.get('is_active', '').strip()
            queryset = ShippingFeeConfig.objects.all()
            
            # 只有当参数不为空时才添加过滤条件
            if carrier:
                queryset = queryset.filter(carrier=carrier)
            
            if volume:
                queryset = queryset.filter(volume=volume)
            
            if region:
                queryset = queryset.filter(region__icontains=region)
            
            if is_active:
                is_active_bool = is_active.lower() == 'true'
                queryset = queryset.filter(is_active=is_active_bool)
            
            # 检查是否有分页参数
            page_param = request.query_params.get('page')
            page_size_param = request.query_params.get('page_size')
            
            # 如果有分页参数，强制使用分页
            if page_param or page_size_param:
                page = self.paginate_queryset(queryset)
                if page is not None:
                    serializer = ShippingFeeConfigSerializer(page, many=True)
                    # 直接返回分页响应，不包装额外的数据结构
                    return self.get_paginated_response(serializer.data)
                else:
                    # 如果分页失败，返回空结果
                    return Response({
                        'count': 0,
                        'next': None,
                        'previous': None,
                        'page_size': int(page_size_param) if page_size_param else 100,
                        'current_page': int(page_param) if page_param else 1,
                        'total_pages': 0,
                        'results': []
                    })
            else:
                # 没有分页参数，返回所有数据
                serializer = ShippingFeeConfigSerializer(queryset, many=True)
                return Response({'code': 200,'message': '获取运费配置成功','data': serializer.data})        
            
        except Exception as e:
            return Response({'code': 500,'message': f'获取运费配置失败: {str(e)}','data': None}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def create(self, request):
        try:
            serializer = ShippingFeeConfigSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'code': 200,'message': '运费配置创建成功','data': serializer.data})
            else:
                return Response({'code': 400,'message': f'数据验证失败: {serializer.errors}','data': None}, status=status.HTTP_400_BAD_REQUEST)
                
        except Exception as e:
            return Response({'code': 500,'message': f'创建运费配置失败: {str(e)}','data': None}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def update(self, request, pk=None):
        try:
            try:
                config = ShippingFeeConfig.objects.get(id=pk)
            except ShippingFeeConfig.DoesNotExist:
                return Response({'code': 404,'message': '运费配置不存在','data': None}, status=status.HTTP_404_NOT_FOUND)
            
            serializer = ShippingFeeConfigSerializer(config, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response({'code': 200,'message': '运费配置更新成功','data': serializer.data})
            else:
                return Response({'code': 400,'message': f'数据验证失败: {serializer.errors}','data': None}, status=status.HTTP_400_BAD_REQUEST) 
        except Exception as e:
            return Response({'code': 500,'message': f'更新运费配置失败: {str(e)}','data': None}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def destroy(self, request, pk=None):
        try:
            try:
                config = ShippingFeeConfig.objects.get(id=pk)
                config.delete()
                return Response({'code': 200,'message': '运费配置删除成功','data': None})       
            except ShippingFeeConfig.DoesNotExist:
                return Response({'code': 404,'message': '运费配置不存在','data': None}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({'code': 500,'message': f'删除运费配置失败: {str(e)}','data': None}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(methods=['POST'], detail=False, url_path='batch_delete')
    def batch_delete(self, request):
        try:
            ids = request.data.get('ids', [])
            if not ids:
                return Response({'code': 400,'message': '请提供要删除的配置ID','data': None}, status=status.HTTP_400_BAD_REQUEST)
            # 批量删除
            deleted_count = ShippingFeeConfig.objects.filter(id__in=ids).delete()[0]
            return Response({'code': 200,'message': f'批量删除成功，共删除 {deleted_count} 条记录','data': None})       
        except Exception as e:
            return Response({'code': 500,'message': f'批量删除运费配置失败: {str(e)}','data': None}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 订单问答视图集
class OrderQAViewSet(viewsets.ModelViewSet):
    """订单问答视图集"""
    queryset = OrderQA.objects.all()
    serializer_class = OrderQASerializer
    permission_classes = [IsAuthenticated]
    pagination_class = MyPageNumberPagination
    
    def get_queryset(self):
        """获取查询集"""
        queryset = OrderQA.objects.all()
        
        # 搜索功能
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(question_no__icontains=search) |
                Q(customer_info__icontains=search) |
                Q(question_summary__icontains=search) |
                Q(sales_person__icontains=search)
            )
        
        # 按时间段筛选
        time_slot = self.request.query_params.get('time_slot', None)
        if time_slot:
            queryset = queryset.filter(time_slot=time_slot)
        
        # 按用户筛选
        user = self.request.query_params.get('user', None)
        if user:
            queryset = queryset.filter(created_by__username__icontains=user)
        
        # 按日期范围筛选
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        if start_date:
            start_date = timezone.make_aware(datetime.strptime(start_date, '%Y-%m-%d'))
            queryset = queryset.filter(create_time__gte=start_date)
        if end_date:
            end_date = timezone.make_aware(datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1))
            queryset = queryset.filter(create_time__lt=end_date)
        
        return queryset.order_by('-create_time')
    
    def perform_create(self, serializer):
        """创建时设置用户"""
        serializer.save(created_by=self.request.user)
    
    def perform_update(self, serializer):
        """更新时设置用户"""
        serializer.save(created_by=self.request.user)
    
    
    @action(methods=['GET'], detail=False, url_path='statistics')
    def get_statistics(self, request):
        """获取订单问答统计信息"""
        try:
            queryset = self.get_queryset()
            
            # 按时间段统计
            time_slot_stats = {}
            for choice in OrderQA.TIME_SLOT_CHOICES:
                count = queryset.filter(time_slot=choice[0]).count()
                time_slot_stats[choice[0]] = {
                    'display': choice[1],
                    'count': count,
                    'quantity': count  # 时间段条数就是数量
                }
            
            # 按用户统计
            user_stats = queryset.values('created_by__username').annotate(
                count=Count('id')
            ).order_by('-count')
            
            # 总体统计
            total_records = queryset.count()
            total_quantity = total_records  # 总条数就是总数量
            
            return Response({
                'code': 200,
                'message': '获取统计信息成功',
                'data': {
                    'time_slot_stats': time_slot_stats,
                    'user_stats': list(user_stats),
                    'total_records': total_records,
                    'total_quantity': total_quantity
                }
            })
        except Exception as e:
            logger.error(f"获取订单问答统计失败: {str(e)}")
            return Response({'code': 500, 'message': f'获取统计信息失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)